<template>
  <view class="quantity-stepper">
    <view 
      class="btn minus" 
      :class="{ disabled: value <= min }"
      @click="onMinus"
    >
      <text>-</text>
    </view>
    <input
      class="input"
      type="number"
      :value="value"
      @input="onInput"
      @blur="onBlur"
    />
    <view 
      class="btn plus" 
      :class="{ disabled: value >= max }"
      @click="onPlus"
    >
      <text>+</text>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    value: {
      type: Number,
      default: 1
    },
    min: {
      type: Number,
      default: 1
    },
    max: {
      type: Number,
      default: 99
    },
    step: {
      type: Number,
      default: 1
    }
  },
  methods: {
    onMinus() {
      if (this.value <= this.min) {
        return;
      }
      const newValue = this.value - this.step;
      this.$emit('input', newValue < this.min ? this.min : newValue);
      this.$emit('change', newValue < this.min ? this.min : newValue);
    },
    onPlus() {
      if (this.value >= this.max) {
        return;
      }
      const newValue = this.value + this.step;
      this.$emit('input', newValue > this.max ? this.max : newValue);
      this.$emit('change', newValue > this.max ? this.max : newValue);
    },
    onInput(e) {
      let value = parseInt(e.detail.value);
      
      if (isNaN(value)) {
        value = this.min;
      }
      
      this.$emit('input', value);
    },
    onBlur(e) {
      let value = parseInt(e.detail.value);
      
      if (isNaN(value)) {
        value = this.min;
      } else if (value < this.min) {
        value = this.min;
      } else if (value > this.max) {
        value = this.max;
      }
      
      this.$emit('input', value);
      this.$emit('change', value);
    }
  }
};
</script>

<style lang="scss">
@import '../styles/variables.scss';

.quantity-stepper {
  display: flex;
  align-items: center;
  
  .btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid $border-color;
    background-color: #fff;
    
    &.minus {
      border-radius: $border-radius-xs 0 0 $border-radius-xs;
    }
    
    &.plus {
      border-radius: 0 $border-radius-xs $border-radius-xs 0;
    }
    
    &.disabled {
      color: $text-color-placeholder;
      background-color: $bg-color-light;
    }
  }
  
  .input {
    width: 80rpx;
    height: 60rpx;
    text-align: center;
    border-top: 1px solid $border-color;
    border-bottom: 1px solid $border-color;
    font-size: $font-size-base;
    background-color: #fff;
  }
}
</style> 